<?php
/**
 * GoodsSpecModel.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/05/12
 * Time: 11:21
 */
namespace app\api\model;

use app\common\Singleton;
use think\Db;

class GoodsSpecModel
{
    use Singleton;

    public function save($flag,$data,$extend=[])
    {
        if(empty($flag))
        {
            // 添加
            $data['create_ts'] = time();
            return Db::name('goods_spec')
                ->insertGetId($data);
        }
        else
        {
            // 编辑
            $data['update_ts'] = time();
            return Db::name('goods_spec')
                ->where('id',$flag)
                ->update($data);
        }
    }

    /**
     * @param $goods_id
     * @param $data
     * @param array $extend
     * @throws \Exception
     */
    public function batchSave($goods_id,$data,$extend=[])
    {
        // $error = [];
        $a = ['goods_id' => $goods_id];
        foreach($data as $v)
        {
            $id = $v['id'];
            unset($v['id']);
            $spec = array_merge($a,$v);
            $status = $this->save($id,$spec);
            if(!$status)
            {
                throw new \Exception("批量保存商品规格失败",2);
            }
        }
    }

    public function getInfoByGoodsId($goods_id,$extend=[])
    {
        $handler = Db::name('goods_spec');
        if(!empty($extend['field']))
        {
            $handler->field($extend['field']);
        }
        return $handler
            ->where('goods_id',$goods_id)
            ->select();
    }
}